#!/usr/bin/env node

const inquirer = require('inquirer');
const fs = require('fs');
const path = require('path');
const fs_extra = require('fs-extra');
const template_name = path.join(__dirname,'templates');

async function main () {
    const res_path = await prompting();
    const file_path = path.join(template_name, res_path.type, res_path.file)
    writing(file_path)
}

function prompting () {

    console.log('Welcome to use dominguito_scaffold');
    const readtypes = fs.readdirSync (template_name); //get the files or directories in a directory.
    const types = readtypes.filter (value => value[0] !== '.'); //filter the dot files.
    const questions_type = [
      {
        type: 'list',
        name: 'type',
        message: 'What type is you need?',
        choices: types,
      },
    ];
    
    const res = inquirer.prompt(questions_type).then((answers) => {
                    const read_dir = fs.readdirSync(path.join(template_name, answers.type)); //get the file after the type is determined. It is the dynamic prompting.
                    const result = read_dir.filter (value => value[0] !== '.');
                    answers.files_name = result;
                    return answers;
                    }).then(answers => {
                        const questions_files = [
                            {
                                type: 'list',
                                name: 'file',
                                message: 'What file is you need?',
                                choices: answers.files_name,
                            },
                        ]
                        const final_result = inquirer.prompt(questions_files).then(res => {
                            const final = Object.assign({},answers, res);
                            return final
                        })
                        return final_result;
                    });

    return res;
}

function writing (src_path) {
    const destDir = process.cwd();
    if(src_path.indexOf("project") !== -1){
        console.log(src_path);
        fs.readdir(src_path, (err, files) => {
            if (err) throw err
            files.forEach(file => {
                fs_extra.copy(path.join(src_path, file), path.join(destDir, file), (err) => {
                    if(err) throw err;
                    console.log(`success to create the file: ${file}`);
                })
            })
          })
    }else if(src_path.indexOf("layout") !== -1) {
        fs.readFile(src_path,(err, data) => {
            if(err) throw err;
            const file_name = src_path.split("/")
            fs.writeFileSync(path.join(destDir, file_name[file_name.length - 1]),data);
        })
    }
}


main()